import bignumber, { type BigNumber } from '@peng_kai/kit/libs/bignumber';
import { useStorage } from '@peng_kai/kit/libs/vueuse';
import { useCurrencyQuery, useHandshakeQuery } from '~/modules/query-client/queries';

export const TEST_CURRENCY: string = 'DIAMOND';

export const useCurrencyStore = defineStore('currency', () => {
  const authed = useAuthed();
  const { currencyQry, balanceQry, cryptoList, cryptoMap, fiatList, fiatMap, currencyList, currencyMap, balanceList, balanceMap } = useCurrencyQuery();
  const { cryptoName } = useCryptoName(computed<any>(() => authed.value ? balanceList.value : currencyList.value));
  const crypto = computed(() => {
    const crypto = balanceList.value?.filter(item => item.currency === cryptoName.value)[0];
    return crypto ? { ...crypto, ...balanceMap.value[crypto.currency] } : undefined;
  });
  const quoteDisplay = useStorage('QUOTE_DISPLAY', false);
  const quoteName = useStorage('QUOTE_NAME', 'USD');
  const quote = computed(() => {
    const quote = fiatMap.value[quoteName.value] || cryptoMap.value[quoteName.value];
    return quote as (typeof quote | undefined);
  });

  const convert = computed(() => {
    const _cryptoMap = cryptoMap.value;
    const _fiatMap = fiatMap.value;

    return (sourceCurrency: string, sourceValue: BigNumber.Value, targetCurrency: string) => {
      if (targetCurrency === 'DIAMOND') {
        targetCurrency = 'USD';
      }
      if (sourceCurrency === targetCurrency)
        return bignumber(sourceValue);

      const scInfo = _fiatMap[sourceCurrency] ?? _cryptoMap[sourceCurrency];
      const tcInfo = _fiatMap[targetCurrency] ?? _cryptoMap[targetCurrency];

      if (!scInfo || !tcInfo)
        return bignumber(0);

      if (scInfo.currency === tcInfo.currency)
        return bignumber(sourceValue);

      return bignumber(sourceValue).times(scInfo.usd_price).div(tcInfo.usd_price);
    };
  });
  const usdConvert = computed(() => {
    const _cryptoMap = cryptoMap.value;
    const _fiatMap = fiatMap.value;

    return (sourceValue: BigNumber.Value, targetCurrency = quoteName.value) => {
      const tcInfo = _fiatMap[targetCurrency] ?? _cryptoMap[targetCurrency];

      if (!tcInfo)
        return bignumber(0);

      if (tcInfo.currency === 'USD')
        return bignumber(sourceValue);

      return bignumber(sourceValue).multipliedBy(tcInfo.usd_price).abs();
    };
  });

  const refetch = () => {
    currencyQry.refetch();
    authed.value && balanceQry.refetch();
  };

  // 初始化币种
  watch(balanceList, (balanceList) => {
    const needInit = balanceList?.length && (!cryptoName.value || !balanceList.find(x => x.currency === cryptoName.value));

    if (needInit)
      cryptoName.value = balanceList?.find(c => ![TEST_CURRENCY].includes(c.currency))?.currency;
  });

  return {
    /** 币种信息查询器 */
    currencyQry,
    /** 用户余额查询器 */
    balanceQry,
    /** 币种(含法定货币和数字货币)List */
    currencyList,
    /** 币种(含法定货币和数字货币)Map */
    currencyMap,

    /** 币种余额列表 */
    balanceList,
    /** 币种余额Map */
    balanceMap,

    /** 当前数字货币名称 */
    cryptoName,
    /** 当前数字货币信息 */
    crypto,
    /** 数字货币列表 */
    cryptoList,
    /** 数字货币Map */
    cryptoMap,

    /** 法定货币列表 */
    fiatList,
    /** 法定货币Map */
    fiatMap,

    /** 是否用已计价币种显示金额 */
    quoteDisplay,
    /** 计价币种名称 */
    quoteName,
    /** 计价币种信息 */
    quote,

    /** 币种价值换算(Any To Any) */
    convert,
    /** 美元价值换算(USD To Any) */
    usdConvert,
    /** 刷新币种\余额 */
    refetch,
  };
});

function useCryptoName(currencyList: Ref<Array<{ currency: string; language: string }> | undefined>) {
  const cryptoName = useStorage('CRYPTO_NAME', '');
  const cryptoNameInitial = ref<string | undefined>(undefined);
  const { handshake } = useHandshakeQuery();
  const countryCryptoName = computed(() => handshake.value?.country_currency);

  // 初始化币种
  // watch(currencyList, (currencyList) => {
  //   if (!currencyList?.length)
  //     return;

  //   const needInit = !cryptoName.value;
  //   if (needInit) {
  //     // 优先使用当前语言对应的币种
  //     const currencyByLang = currencyList.find(item => item.language?.includes(appValues.language))?.currency;
  //     cryptoName.value = cryptoNameInitial.value = envs.isTg ? 'TON' : (currencyByLang || 'USDT');
  //   }

  //   // 当cryptoName不在balanceList中时，重置为第一个非测试币种
  //   const needReset = !currencyList.find(x => x.currency === cryptoName.value);
  //   if (needReset) {
  //     cryptoName.value = cryptoNameInitial.value = currencyList?.find(c => ![TEST_CURRENCY].includes(c.currency))?.currency;
  //   }
  // });

  // 初始化币种
  watchEffect(() => {
    const _currencyList = currencyList.value;
    const _countryCryptoName = countryCryptoName.value;

    if (!_currencyList?.length)
      return;

    const canInit = !cryptoName.value && typeof _countryCryptoName === 'string';
    if (canInit) {
      const currencyByLang = _currencyList.find(item => item.language?.includes(appValues.language))?.currency;
      // 优先使用接口返回的国家币种
      const finalName = envs.isTg ? 'TON' : (_countryCryptoName || currencyByLang || 'USDT');
      cryptoName.value = finalName;
      cryptoNameInitial.value = finalName;
    }

    // 当cryptoName不在balanceList中时，重置为第一个非测试币种
    const needReset = cryptoName.value && !_currencyList.find(x => x.currency === cryptoName.value);
    if (needReset) {
      cryptoName.value = cryptoNameInitial.value = _currencyList?.find(c => ![TEST_CURRENCY].includes(c.currency))?.currency;
    }
  });

  return { cryptoName, cryptoNameInitial };
}
